package main;

import io.seata.rm.RMClient;
import io.seata.tm.TMClient;
import io.seata.tm.api.GlobalTransaction;
import io.seata.tm.api.GlobalTransactionContext;
import mapper.JianMapper;
import mapper.NongMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.transaction.TransactionException;
import utils.FactoryUtils;

public class Demo {

    static {
        //指定一个应用唯一id值 随便写 想写啥写啥
        String applicationId = "abc";
        //指定默认的事务分组 要和file.conf中指定的一致 使用默认的即可
        String groupId = "default_tx_group";
        TMClient.init(applicationId, groupId);
        RMClient.init(applicationId, groupId);
    }

    public static void main(String[] args) {
        SqlSessionFactory nongSqlSessionFactory = FactoryUtils.nongSqlSessionFactory();
        SqlSessionFactory jianSqlSessionFactory = FactoryUtils.jianSqlSessionFactory();
        SqlSession nongSession = nongSqlSessionFactory.openSession(true);
        NongMapper nongMapper = nongSession.getMapper(NongMapper.class);
        SqlSession jianSession = jianSqlSessionFactory.openSession(true);
        JianMapper jianMapper = jianSession.getMapper(JianMapper.class);
        //获取全局事务对象
        GlobalTransaction globalTransaction = GlobalTransactionContext.getCurrentOrCreate();
        try {
            globalTransaction.begin();
            nongMapper.nonghang(100);
            int i =10/0;
            jianMapper.jianhang(100);
            globalTransaction.commit();//提交事务
        } catch (Exception e) {
            e.printStackTrace();
            try {
                globalTransaction.rollback(); //回滚事务
            } catch (TransactionException ex) {
                ex.printStackTrace();
                throw new RuntimeException(ex);
            } catch (io.seata.core.exception.TransactionException ex) {
                ex.printStackTrace();
            }
        }
        // //关闭资源 省略
        jianSession.close();
        nongSession.close();
    }
}
